package com.ruoyi.rsikManage.service.Impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.electricity.domain.CoalMineInfo;
import com.ruoyi.electricity.mapper.CoalMineInfoMapper;
import com.ruoyi.rsikManage.domain.*;
import com.ruoyi.rsikManage.domain.algoTree.AlgoCountVo;
import com.ruoyi.rsikManage.domain.vo.AlgoAndMonitors;
import com.ruoyi.rsikManage.domain.algoTree.AlgoTreeVo;
import com.ruoyi.rsikManage.domain.vo.MonitorAndAlgos;
import com.ruoyi.rsikManage.mapper.AlgorithmMapper;
import com.ruoyi.rsikManage.mapper.MonitorPointMapper;
import com.ruoyi.rsikManage.mapper.TVideoStandPlaceMapper;
import com.ruoyi.rsikManage.service.AlgorithmService;
import com.ruoyi.rsikManage.service.ITUnitConfigService;
import com.ruoyi.rsikManage.service.JyService;
import com.ruoyi.rsikManage.service.MonitorPointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Service
public class AlgorithmServiceImpl implements AlgorithmService {
    @Autowired
    private JyService jyService;

    @Autowired
    private MonitorPointService monitorPointService;

    @Autowired
    private MonitorPointMapper monitorPointMapper;
    @Autowired
    TVideoStandPlaceMapper tVideoStandPlaceMapper;
    @Autowired
    AlgorithmMapper algorithmMapper;

    @Autowired
    CoalMineInfoMapper coalMineInfoMapper;

    @Autowired
    private ITUnitConfigService iTUnitConfigService;

    @Override
    public List<AlgoCountVo> totalNumberOfAlgosInAlgoTree() {
        return algorithmMapper.totalNumberOfAlgosInAlgoTree();
    }

    @Override
    public List<AlgoCountVo> totalNumberOfAlgosInAlgoTreeForUnitCodes(Long unitCode) {
        return algorithmMapper.totalNumberOfAlgosInAlgoTreeForUnitCodes(unitCode);
    }

    @Override
    public List<AlgoCountVo> totalNumberOfAlgosInAlgoTreeGroup() {
        return algorithmMapper.totalNumberOfAlgosInAlgoTreeGroup();
    }

    /**
     * 算法-监控点
     * @param algorithm
     * @return
     */
    @Override
    public List<AlgoAndMonitors> algorithmAndMonitors(Algorithm algorithm) {
        List<AlgoAndMonitors> resList = new ArrayList<>();
        String jsonStr = jyService.getInstalledAlgorithms();
        JSONArray installedAlgosJsonArr = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        for (int i = 0; i < installedAlgosJsonArr.size(); i++) {
            Algorithm algo = new Algorithm();
            JSONObject installedAlgosJsonObject = installedAlgosJsonArr.getJSONObject(i);
            algo.setAlgoId(installedAlgosJsonObject.getString("algo_id"));
            algo.setAlgoName(installedAlgosJsonObject.getString("algo_name"));

            if (algorithm.getAlgoName() != null && algorithm.getAlgoName() != "" && !algo.getAlgoName().contains(algorithm.getAlgoName())){
                continue;
            }
            List<MonitorPoint> monitorsInTheAlgorithm = monitorsInTheAlgorithm(algo.getAlgoId());
            //
            if (monitorsInTheAlgorithm != null && monitorsInTheAlgorithm.size() > 0) {
                for (MonitorPoint monitor : monitorsInTheAlgorithm) {
                    AlgoAndMonitors algoAndMonitors = new AlgoAndMonitors();
                    algoAndMonitors.setAlgoName(algo.getAlgoName());
                    algoAndMonitors.setMonitorName(monitor.getName());
                    algoAndMonitors.setMonitorId(monitor.getApeId());
                    algoAndMonitors.setIsEnable(monitor.getIsEnabled());
                    algoAndMonitors.setIsOnline(monitor.getIsOnline());
                    resList.add(algoAndMonitors);
                }
            }else {
                AlgoAndMonitors algoAndMonitors = new AlgoAndMonitors();
                algoAndMonitors.setAlgoName(algo.getAlgoName());
                resList.add(algoAndMonitors);
            }

        }
        return resList;
    }

    /**
     * 监控点-算法
     * @param monitorName
     * @return
     */
    @Override
    public List<MonitorAndAlgos> monitorAndAlgorithmV1(String monitorName) {
        List<MonitorAndAlgos> resList = new ArrayList<>();
        //1.查询所有分析任务
        String jsonStr = jyService.getVideoAnalysisTasks();
        //2查询所有算法
        String jsonStr2 = jyService.getInstalledAlgorithms();
        JSONArray videoAnalysisTasksJsonArray = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        //2.遍历所有的监控点
        List<MonitorPoint> monitorPointList = monitorPointService.selectAllMonitorPoints();
        for (MonitorPoint m : monitorPointList) {
            String name = m.getName();
            if (monitorName != null && monitorName != "" && !name.contains(monitorName)) {
                continue;
            }
            String monitorId = m.getApeId();
            //2.1筛选出source_id是monitorId的分析任务,得到一个algorithm_id集合
            HashSet<String> algorithmIdSet = new HashSet<>();
            for (int i = 0; i < videoAnalysisTasksJsonArray.size(); i++) {
                JSONObject videoAnalysisTaskJsonObject = videoAnalysisTasksJsonArray.getJSONObject(i);
                boolean flag = videoAnalysisTaskJsonObject.getString("source_id").equals(monitorId);
                if (flag == true) {
                    String algorithmId = videoAnalysisTaskJsonObject.getString("algorithm_id");
                    algorithmIdSet.add(algorithmId);
                }
            }
            JSONArray installedAlgosJsonArr = JSONObject.parseObject(jsonStr2).getJSONObject("data").getJSONArray("data");
            boolean isHaveAlgos = false;
            for (int i = 0; i < installedAlgosJsonArr.size(); i++) {
                JSONObject installedAlgosJsonObject = installedAlgosJsonArr.getJSONObject(i);
                boolean isHaveThisAlgo = algorithmIdSet.contains(installedAlgosJsonObject.getString("algo_id").substring(1));
                if (isHaveThisAlgo == true) {
                    //
                    MonitorAndAlgos monitorAndAlgos = new MonitorAndAlgos();
                    monitorAndAlgos.setMonitorName(name);
                    monitorAndAlgos.setAlgoId(installedAlgosJsonObject.getString("algo_id"));
                    monitorAndAlgos.setAlgoName(installedAlgosJsonObject.getString("algo_name"));
                    monitorAndAlgos.setAlgoType(installedAlgosJsonObject.getString("algo_type"));
                    monitorAndAlgos.setInstallTime(installedAlgosJsonObject.getString("install_time"));
                    resList.add(monitorAndAlgos);
                    isHaveAlgos = true;
                }
            }
            if (!isHaveAlgos) {
                MonitorAndAlgos monitorAndAlgos = new MonitorAndAlgos();
                monitorAndAlgos.setMonitorName(name);
                resList.add(monitorAndAlgos);
//                System.out.println(monitorAndAlgos.toString());
            }
        }
        return resList;
    }

    /**
     * 监控点-算法
     * @param monitorName
     * @return
     */
    @Override
    public List<MonitorAndAlgos> monitorAndAlgorithm(List<Long> unitCode,String monitorName) {
        List<MonitorAndAlgos> resList = new ArrayList<>();

        TUnitConfig tUnitConfig = new TUnitConfig();
        tUnitConfig.setUnitCodes(unitCode);
        List<TUnitConfig> tUnitConfigs = iTUnitConfigService.selectTUnitConfigList(tUnitConfig);
        TUnitConfig tUnit = tUnitConfigs.get(0);
        //1.查询所有分析任务
        String jsonStr = jyService.getVideoAnalysisTasksForUnitCodes(tUnit);
        //2查询所有算法
        String jsonStr2 = jyService.getInstalledAlgorithmsForUnitCodes(tUnit);
        JSONArray videoAnalysisTasksJsonArray = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        //2.遍历所有的监控点
        List<MonitorPoint> monitorPointList = monitorPointService.selectAllMonitorPoints();
        for (MonitorPoint m : monitorPointList) {
            String name = m.getName();
            if (monitorName != null && monitorName != "" && !name.contains(monitorName)) {
                continue;
            }
            String monitorId = m.getApeId();
            //2.1筛选出source_id是monitorId的分析任务,得到一个algorithm_id集合
            HashSet<String> algorithmIdSet = new HashSet<>();
            for (int i = 0; i < videoAnalysisTasksJsonArray.size(); i++) {
                JSONObject videoAnalysisTaskJsonObject = videoAnalysisTasksJsonArray.getJSONObject(i);
                boolean flag = videoAnalysisTaskJsonObject.getString("source_id").equals(monitorId);
                if (flag == true) {
                    String algorithmId = videoAnalysisTaskJsonObject.getString("algorithm_id");
                    algorithmIdSet.add(algorithmId);
                }
            }
            JSONArray installedAlgosJsonArr = JSONObject.parseObject(jsonStr2).getJSONObject("data").getJSONArray("data");
            boolean isHaveAlgos = false;
            for (int i = 0; i < installedAlgosJsonArr.size(); i++) {
                JSONObject installedAlgosJsonObject = installedAlgosJsonArr.getJSONObject(i);
                boolean isHaveThisAlgo = algorithmIdSet.contains(installedAlgosJsonObject.getString("algo_id").substring(1));
                if (isHaveThisAlgo == true) {
                    //
                    MonitorAndAlgos monitorAndAlgos = new MonitorAndAlgos();
                    monitorAndAlgos.setMonitorName(name);
                    monitorAndAlgos.setAlgoId(installedAlgosJsonObject.getString("algo_id"));
                    monitorAndAlgos.setAlgoName(installedAlgosJsonObject.getString("algo_name"));
                    monitorAndAlgos.setAlgoType(installedAlgosJsonObject.getString("algo_type"));
                    monitorAndAlgos.setInstallTime(installedAlgosJsonObject.getString("install_time"));
                    resList.add(monitorAndAlgos);
                    isHaveAlgos = true;
                }
            }
            if (!isHaveAlgos) {
                MonitorAndAlgos monitorAndAlgos = new MonitorAndAlgos();
                monitorAndAlgos.setMonitorName(name);
                resList.add(monitorAndAlgos);
//                System.out.println(monitorAndAlgos.toString());
            }
        }
        return resList;
    }

    @Override
    public List<PlaceCategory> placeCategoryAndPlaceAndAlgorithms2() {
        return algorithmMapper.placeCategoryAndPlaceAndAlgorithms2();
    }

    /**
     * 算法列表
     * @param algorithm
     * @return
     */
    @Override
    public List<Algorithm> algoList(Algorithm algorithm) {
        List<Algorithm> algorithmList = new ArrayList<>();
        String jsonStr = jyService.getInstalledAlgorithms();
        JSONArray installedAlgosJsonArr = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        for (int i = 0; i < installedAlgosJsonArr.size(); i++) {
            Algorithm algo = new Algorithm();
            JSONObject installedAlgosJsonObject = installedAlgosJsonArr.getJSONObject(i);
            algo.setAlgoId(installedAlgosJsonObject.getString("algo_id"));
            algo.setAlgoName(installedAlgosJsonObject.getString("algo_name"));
            algo.setAlgoType(installedAlgosJsonObject.getString("algo_type"));
            algo.setInstallTime(installedAlgosJsonObject.getString("install_time"));
            if (algorithm.getAlgoName() == null) {
                algorithmList.add(algo);
            }else if (algorithm.getAlgoName().equals(algo.getAlgoName())){
                algorithmList.add(algo);
            }
        }

        return algorithmList;
    }

    @Override
    public List<MonitorPoint> monitorsInTheAlgorithm(String algorithmId) {
        //1.查询所有分析任务
        String jsonStr = jyService.getVideoAnalysisTasks();
        JSONArray videoAnalysisTasksJsonArray = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        //2.筛选出algorithm_id是algorithmId的分析任务,得到一组source_id
        HashSet<String> sourceIdSet = new HashSet<>();
        for (int i = 0; i < videoAnalysisTasksJsonArray.size(); i++) {
            JSONObject videoAnalysisTaskJsonObject = videoAnalysisTasksJsonArray.getJSONObject(i);
            boolean flag = videoAnalysisTaskJsonObject.getString("algorithm_id").equals(algorithmId.substring(1));
            if (flag == true) {
                String sourceId = videoAnalysisTaskJsonObject.getString("source_id");
                sourceIdSet.add(sourceId);
            }
        }

        List<MonitorPoint> monitorPoints = new ArrayList<>();
        if (!sourceIdSet.isEmpty()) {
            //3.查询ape_id是这组source_id之一的监控点
            monitorPoints =  monitorPointMapper.selectMonitorPointsInApeIdSet(sourceIdSet);

        }
        return monitorPoints;
    }

    @Override
    public List<Algorithm> algorithmsInTheMonitor(String monitorId) {
        //1.查询所有分析任务
        String jsonStr = jyService.getVideoAnalysisTasks();
        JSONArray videoAnalysisTasksJsonArray = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        //2.筛选出source_id是monitorId的分析任务,得到一个algorithm_id集合
        HashSet<String> algorithmIdSet = new HashSet<>();
        for (int i = 0; i < videoAnalysisTasksJsonArray.size(); i++) {
            JSONObject videoAnalysisTaskJsonObject = videoAnalysisTasksJsonArray.getJSONObject(i);
            boolean flag = videoAnalysisTaskJsonObject.getString("source_id").equals(monitorId);
            if (flag == true) {
                String algorithmId = videoAnalysisTaskJsonObject.getString("algorithm_id");
                algorithmIdSet.add(algorithmId);
            }
        }
        //3.查询所有算法，筛选出algo_id存在于algorithmIdSet集合的算法
        List<Algorithm> algorithmList = new ArrayList<>();
        String jsonStr2 = jyService.getInstalledAlgorithms();
        JSONArray installedAlgosJsonArr = JSONObject.parseObject(jsonStr2).getJSONObject("data").getJSONArray("data");
        for (int i = 0; i < installedAlgosJsonArr.size(); i++) {
            JSONObject installedAlgosJsonObject = installedAlgosJsonArr.getJSONObject(i);
            boolean flag = algorithmIdSet.contains(installedAlgosJsonObject.getString("algo_id").substring(1));
            if (flag == true) {
                Algorithm algo = new Algorithm();
                algo.setAlgoId(installedAlgosJsonObject.getString("algo_id"));
                algo.setAlgoName(installedAlgosJsonObject.getString("algo_name"));
                algo.setAlgoType(installedAlgosJsonObject.getString("algo_type"));
                algo.setInstallTime(installedAlgosJsonObject.getString("install_time"));
                algorithmList.add(algo);
            }
        }
        return algorithmList;
    }

    @Override
    public List<Algorithm> algorithmsInTheMonitorForUnitCodes(String monitorId) {
        //1.查询所有分析任务
        String jsonStr = jyService.getVideoAnalysisTasks();
        JSONArray videoAnalysisTasksJsonArray = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        //2.筛选出source_id是monitorId的分析任务,得到一个algorithm_id集合
        HashSet<String> algorithmIdSet = new HashSet<>();
        for (int i = 0; i < videoAnalysisTasksJsonArray.size(); i++) {
            JSONObject videoAnalysisTaskJsonObject = videoAnalysisTasksJsonArray.getJSONObject(i);
            boolean flag = videoAnalysisTaskJsonObject.getString("source_id").equals(monitorId);
            if (flag == true) {
                String algorithmId = videoAnalysisTaskJsonObject.getString("algorithm_id");
                algorithmIdSet.add(algorithmId);
            }
        }
        //3.查询所有算法，筛选出algo_id存在于algorithmIdSet集合的算法
        List<Algorithm> algorithmList = new ArrayList<>();
        String jsonStr2 = jyService.getInstalledAlgorithms();
        JSONArray installedAlgosJsonArr = JSONObject.parseObject(jsonStr2).getJSONObject("data").getJSONArray("data");
        for (int i = 0; i < installedAlgosJsonArr.size(); i++) {
            JSONObject installedAlgosJsonObject = installedAlgosJsonArr.getJSONObject(i);
            boolean flag = algorithmIdSet.contains(installedAlgosJsonObject.getString("algo_id").substring(1));
            if (flag == true) {
                Algorithm algo = new Algorithm();
                algo.setAlgoId(installedAlgosJsonObject.getString("algo_id"));
                algo.setAlgoName(installedAlgosJsonObject.getString("algo_name"));
                algo.setAlgoType(installedAlgosJsonObject.getString("algo_type"));
                algo.setInstallTime(installedAlgosJsonObject.getString("install_time"));
                algorithmList.add(algo);
            }
        }
        return algorithmList;
    }

    @Override
    public AlgoTreeVo selectAlgoTree(Integer categoryId) {
        return algorithmMapper.selectAlgoTree(categoryId);
    }

    @Override
    public AlgoTreeVo selectAlgoTreeV2(Integer categoryId,Long unitCode) {
        return algorithmMapper.selectAlgoTreeV2(categoryId,unitCode,null);
    }

    @Override
    public AlgoScenarioRes selectAlgoScenarioList(String category, Date startTime, Date endTime) {

        CoalMineInfo coalMineInfo = new CoalMineInfo();
        coalMineInfo.setItem("煤矿编码");
        coalMineInfo.setConfigurationType("煤矿基础信息");
        List<CoalMineInfo> coalMineInfos = coalMineInfoMapper.selectCoalMineInfoList(coalMineInfo);
        String unitCode = coalMineInfos.get(0).getValue();
        return algorithmMapper.selectAlgoScenarioList(unitCode,category, startTime, endTime);
    }

    @Override
    public List<CategoryAlarmCount> countCategoryAlarm(Date startTime, Date endTime) {
        return algorithmMapper.countCategoryAlarm(startTime, endTime);
    }

    /**
     * 场所类别-场所-算法(算法树)
     * @return
     */
//    @Override
//    public List<PlaceCategory> placeCategoryAndPlaceAndAlgorithms() {
//        List<PlaceCategory> resList = new ArrayList<>();
//        String placeCategoryDicVal = "10";
//        //查询该标准文件下有哪些场所类别
//        List<PlaceCategory> placeChildLevelDicList = tVideoStandPlaceMapper.selectPlaceCategoryDicList("t_video_child_level", placeCategoryDicVal);
//
//        for (PlaceCategory placeChildLevelDic : placeChildLevelDicList) {
//            //场所类别
//            String placeChildLevelDicKey = placeChildLevelDic.getDicKey();
//            String placeChildLevelDicVal = placeChildLevelDic.getDicValue();
//            //该场所列别下的场所-算法
//            PlaceCategory category = new PlaceCategory();
//            category.setCategory(placeChildLevelDicKey);
//            List<PlaceAndAlgorithms> placeAndAlgorithmslist = selectPlaceAndAlgorithms(placeCategoryDicVal, placeChildLevelDicVal);
//            int categoryAlgorithmCount = 0;
//            for (PlaceAndAlgorithms p : placeAndAlgorithmslist) {
//                categoryAlgorithmCount += p.getPlaceAlgoCount();
//            }
//            category.setPlaceAndAlgorithmsList(placeAndAlgorithmslist);
//            category.setCategoryAlgorithmCount(categoryAlgorithmCount);
//            resList.add(category);
//        }
//        return resList;
//    }

    /**
     * 场所-算法
     *
     * 返回的hashMap中key是场所名称， value 是 该场所下对应的算法列表
     * @param parentCategoryDicVal
     * @param childCategoryDicVal
     * @return
     */
//    public List<PlaceAndAlgorithms> selectPlaceAndAlgorithms(String parentCategoryDicVal, String childCategoryDicVal) {
//        List<PlaceAndAlgorithms>  resList = new ArrayList<>();
//        //配置查询场所时的参数对象
//        TVideoStandPlace paramPlace = new TVideoStandPlace();
//        paramPlace.setTVideoChildLevel(childCategoryDicVal);
//        paramPlace.setTVideoParentLevel(parentCategoryDicVal);
//        //先查场所
//        List<TVideoStandPlace> placeList = tVideoStandPlaceMapper.selectTVideoStandPlaceList(paramPlace);
//        System.out.println("场所类别" + childCategoryDicVal + "下的场所 =============================");
//        placeList.forEach(System.out::println);
//        //再查场所对应的算法
//        for (TVideoStandPlace place : placeList) {
//            List<Algorithm> algorithms = algorithmMapper.selectAlgorithmsByPlaceId(place.getId());
//            PlaceAndAlgorithms placeAndAlgorithms = new PlaceAndAlgorithms();
//            placeAndAlgorithms.setPlace(place.getAddress());
//            placeAndAlgorithms.setAlgorithmList(algorithms);
//            placeAndAlgorithms.setPlaceAlgoCount(algorithms.size());
//            resList.add(placeAndAlgorithms);
//        }
//        return resList;
//    }

}
